<?php

use Cekurte\App,
	Cekurte\Controller\Crud,
	Cekurte\Controller\Action;

class TaskController extends Action implements Crud
{	
	protected function setup()
	{
		$this->form		= App::getForm('Task');
		$this->model 	= App::getModel('Task');
	}
	
	public function indexAction()
	{
		$this->redirector->gotoSimple( 'list', 'task' );
	}
	
	public function createAction()
	{
		if( $this->getRequest()->isPost() ) 
        {
        	$data 		= $this->getRequest()->getPost();
        	
        	$result 	= $this->model->save( $data );
        	
        	$messageKey = ($result === false) ? 'create.message.error' : 'create.message.success';
        	
        	$this->flashMessenger->addMessage( $this->translate->_( $messageKey ) );
        	
        	if( $result )
        	{
        		$this->redirector->gotoSimple( 'list', 'task' );
        	}
        	
        	$this->form->populate( $data );
        }
        
		$this->view->form = $this->form;
	}

	public function retrieveAction()
	{
		$registry = $this->model->findById( $this->id );
		
		if( empty( $registry ) )
		{
			$this->flashMessenger->addMessage( $this->translate->_( 'registry.empty' ) );
			
			$this->redirector->gotoSimple( 'list', 'task' );
		}
		
		$this->view->registry = $registry;
	}

	public function updateAction()
	{
		if( $this->getRequest()->isPost() ) 
        {
        	$data 		= $this->getRequest()->getPost();
        	
        	$result 	= $this->model->save( $data, $this->id );
        	
        	$messageKey = ($result === false) ? 'update.message.error' : 'update.message.success';
        	
        	$this->flashMessenger->addMessage( $this->translate->_( $messageKey ) );
        	
        	if( $result )
        	{
        		$this->redirector->gotoSimple( 'list', 'task' );
        	}
        }
        else
        {
        	$registry = $this->model->findById( $this->id );
        	
        	if( empty( $registry ) )
        	{
        		$this->flashMessenger->addMessage( $this->translate->_( 'registry.empty' ) );
        		
        		$this->redirector->gotoSimple( 'list', 'task' );
        	}
        	
        	$this->form->populate( $registry );
        }
        
		$this->view->form = $this->form;
	}

	public function deleteAction()
	{
		$this->layout->disableLayout();
		
		$result		= $this->model->delete( array( 'id' => $this->id ) );
		
		$messageKey = ( $result === false ) ? 'delete.message.error' : 'delete.message.success';
		
		$this->flashMessenger->addMessage( $this->translate->_( $messageKey ) );
		
		$this->redirector->gotoSimple( 'list', 'task' );
	}
	
	public function listAction()
	{
		$this->view->registry = $this->model->getAll();
	}
}